﻿using System;
using System.Collections.Generic;
using System.Text;
using Quartz;
using Quartz.Impl;
using System.Threading;
using AppToolKit.Core.Context.Spring;
using BLL.Business;
using System.Data;
using Common.Logging;
using Utility;
using BLL.Action.Core.Base;

namespace BLL.Action.Job
{
    [AutoWiring]
    public class JobManager
    {
        private IScheduler sched;
        private const string TaskListID = "tasklist_code";
        private const string Time = "time";
        private const string JOB = "job_action";
        ILog log = LogManager.GetLogger(LogDefault.AppDebug);
        [AutoWiring]
        public ContextAware ContextAwareHolder { get; set; }
        [AutoWiring]
        public TaskListBusiness TaskListBusinessHolder { get; set; }

        public  void Run()
        {
            ISchedulerFactory sf = new StdSchedulerFactory();
            sched = sf.GetScheduler();
           DataSet ds=TaskListBusinessHolder.GetDistinctTaskList();
          if(ds.Tables.Count>0)
            log.Debug(string.Format("dataset count:{0}",ds.Tables[0].Rows.Count));
          else
              log.Debug(string.Format("dataset count:0"));
            JobDetail job =null;
           foreach (DataRow dr in ds.Tables[0].Rows)
           {
               job = new JobDetail(dr[TaskListID].ToString(), "group1", typeof(JobDefault));

               log.Debug(string.Format("time:{0}", dr[Time]));

               CronTrigger trigger = new CronTrigger(dr[TaskListID].ToString(), "group1", dr[Time].ToString());


               job.JobDataMap.Add(JobBase.ContextAware_Filed, ContextAwareHolder);
               sched.ScheduleJob(job, trigger);
           }
           //job = new JobDetail("SystemJob", "group1", typeof(SystemJob));
           //CronTrigger trigger1 = new CronTrigger("SystemJob", "group1", "0/10 * * * * ?");


           //job.JobDataMap.Add(JobBase.ContextAware_Filed, ContextAwareHolder);
           //sched.ScheduleJob(job, trigger1);
           sched.Start();

           
        }
        public void OnStop()
        {
            if (sched != null)
                sched.Shutdown(true);
        }
    }
}
